package com.deceive.demo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.RequiresApi;


public class WebViewActivity extends Activity {
    private WebView webView;
    public static String URL = "url";
    private String url;

    public static void startMyWebViewActivity(Context activity, String loadUrl) {
        Intent intent = new Intent(activity, WebViewActivity.class).putExtra(URL, loadUrl);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        webView = new WebView(this);
        setContentView(webView);
        WebSettings webSetting = webView.getSettings();
        webSetting.setDatabaseEnabled(true);
        webSetting.setJavaScriptEnabled(true);

        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);

        webSetting.setAllowFileAccess(true);

        webSetting.setSupportZoom(true);
        webSetting.setDisplayZoomControls(false);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setLoadWithOverviewMode(true);
        webSetting.setBuiltInZoomControls(true);

        webSetting.setSupportMultipleWindows(true);
        webSetting.setCacheMode(WebSettings.LOAD_DEFAULT);

        webSetting.setUseWideViewPort(true);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);

        webSetting.setDomStorageEnabled(true);
        webSetting.setGeolocationEnabled(true);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                Log.i("sdfbeiisos", "onPageStarted: " + url);
                getCookiesFromWebView(url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.i("sdfbeiisos", "onPageFinished: " + url);
                getCookiesFromWebView(url);
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
                Log.i("sdfbeiisos", "onLoadResource: " + url);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                Log.i("sdfbeiisos", "onReceivedError: " + url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    Log.i("sdfbeiisos", "shouldOverrideUrlLoading: " + request.getUrl());

                    getCookiesFromWebView(request.getUrl().toString());

                }
                return true;
//                try {
//                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//                    startActivity(intent);
//                    finish();
//                    return true;
//                } catch (Exception e) {// 防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
//                    return true;// 没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
//                }
                // TODO Auto-generated method stub
                // 返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                // view.loadUrl(uri.toString());
            }


        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }

        });
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                                        long contentLength) {
                Intent intent = new Intent();
                // 设置意图动作为打开浏览器
                intent.setAction(Intent.ACTION_VIEW);
                // 声明一个Uri
                Uri uri = Uri.parse(url);
                intent.setData(uri);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        webView.addJavascriptInterface(new JsInterface(), "jsBridge");
        webView.addJavascriptInterface(new JsInterface(), "android");
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setSupportMultipleWindows(true);
        url = getIntent().getStringExtra("url");
        webView.loadUrl(url);
        //getCookiesFromWebView();
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    private void getCookiesFromWebView(String murl) {
        // 获取 CookieManager 实例
        CookieManager cookieManager = CookieManager.getInstance();

        // 获取指定 URL 的所有 cookies
        String cookies = cookieManager.getCookie(murl);

        // 输出获取的 cookies
        Log.i("sdfbeiisos", "getCookiesFromWebView: " + cookies);
    }

    public class JsInterface {
        // Android 调用 Js 方法1 中的返回值
        @JavascriptInterface
        public void postMessage(String name, String data) {
            if (TextUtils.isEmpty(name) || TextUtils.isEmpty(data)) {
                return;
            }
            if ("openWindow".equals(name)) {
//                Intent intent = new Intent(WebViewOneActivity.this, WebActivity.class);
//                intent.putExtra("url", data);
//                startActivity(intent);
            }
        }
    }
}
